package com.shinewind.info.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Matcher;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shinewind.common.constant.messageConstant;
import com.shinewind.home.service.IUserInfoMappingService;
import com.shinewind.info.service.*;
import com.shinewind.pojo.dto.AdminArticleDto;
import com.shinewind.pojo.dto.AdminModelDto;
import com.shinewind.pojo.entity.*;
import com.shinewind.pojo.result.Result;
import com.shinewind.pojo.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@DubboService
public class InfoAdminServiceImpl implements IInfoAdminService {
    @Autowired
    private IUserDetailService iUserDetailService;
    @Autowired
    private IUserInfoService iUserInfoService;
    @Autowired
    private IArticleService iArticleService;
    @Autowired
    private IUserFollowService iUserFollowService;
    @Autowired
    private ICommentService iCommentService;
    @Autowired
    private IUserRoleService iUserRoleService;
    @DubboReference
    private IUserInfoMappingService iUserInfoMappingService;
    @Autowired
    private IModelTypeService iModelTypeService;
    @Autowired
    private IModelInfoService iModelInfoService;

    @Override
    public PageVo<AdminUserListVo> getUserList(Integer current,Integer pageSize,
                                               String userName,String nickName,
                                               String role,String telePhoneStatus) {
        List<UserInfo> userInfoList;
        System.out.println("userName:"+userName);
        System.out.println("nickName:"+nickName);
        System.out.println("telePhoneStatus:"+telePhoneStatus);
        if((userName != null && !userName.trim().equals("")) || (nickName != null && !nickName.trim().equals(""))){
            userInfoList = iUserInfoService.lambdaQuery().and(i ->
                                    i.like(userName != null && !userName.trim().equals(""),
                                    UserInfo::getUserName,userName)
                                    .like(nickName != null && !nickName.trim().equals(""),
                                    UserInfo::getNickName,nickName)).list();
        }
        else{
            userInfoList = iUserInfoService.lambdaQuery().list();
        }

        List<AdminUserListVo> userListVoList = userInfoList.stream().map(userInfo -> {
            AdminUserListVo adminUserListVo = AdminUserListVo.builder().build();
            BeanUtils.copyProperties(userInfo,adminUserListVo);
            //电话
            if(ObjectUtil.isNull(adminUserListVo.getTelePhone())){
                adminUserListVo.setTelePhone("false");
            }
            //密码
            if(ObjectUtil.isNull(adminUserListVo.getPassWord())){
                adminUserListVo.setPassWord("false");
            }
            //查询用户角色
            if(iUserRoleService.lambdaQuery().eq(UserRole::getUId,userInfo.getUId()).count() > 0){
                List<UserRole> userRoles = iUserRoleService.lambdaQuery().eq(UserRole::getUId,userInfo.getUId()).list();
                List<String> roles = userRoles.stream().map(Role -> {return Role.getRole();}).collect(Collectors.toList());
                System.out.println("roles:"+roles);
                if(roles.indexOf("ROLE_ADMIN") != -1){
                    adminUserListVo.setRole("admin");
                }
                else{
                    adminUserListVo.setRole("user");
                }
            }
            else{
                adminUserListVo.setRole("unassigned");
            }
            //根据role、password、telephone判断账户是否可用
            if((StrUtil.isNotBlank(userInfo.getPassWord()) && ObjectUtil.isNotNull(userInfo.getPassWord())) &&
                    BooleanUtil.isTrue(!adminUserListVo.getRole().equals("unassigned")) &&
                    (StrUtil.isNotBlank(userInfo.getTelePhone()) && ObjectUtil.isNotNull(userInfo.getTelePhone()))){
                adminUserListVo.setStatus(true);
            }
            else{
                adminUserListVo.setStatus(false);
            }
            //用户头像
            adminUserListVo.setAvatar(iUserDetailService.getUserDetailById(userInfo.getUId()).getAvatar());
            //个人签名
            adminUserListVo.setSign(iUserDetailService.getUserDetailById(userInfo.getUId()).getSign());
            return adminUserListVo;
        }).collect(Collectors.toList());
        System.out.println("role:"+role);
        System.out.println("userListVoList:"+userListVoList);
        //角色
        if(role != null){
            if("unassigned".equals(role)){
                userListVoList = userListVoList.stream().filter(user ->{
                    return user.getRole().equals("unassigned");
                }).collect(Collectors.toList());
            }
            else if("ROLE_ADMIN".equals(role)){
                userListVoList = userListVoList.stream().filter(user ->{
                    return user.getRole().equals("admin");
                }).collect(Collectors.toList());
            }
            else if("ROLE_USER".equals(role)){
                userListVoList = userListVoList.stream().filter(user ->{
                    return user.getRole().equals("user");
                }).collect(Collectors.toList());
            }
        }
        //电话
        if(telePhoneStatus != null){
            if("true".equals(telePhoneStatus)){
                userListVoList = userListVoList.stream().filter(user ->{
                    return !(user.getTelePhone().equals("false"));
                }).collect(Collectors.toList());
            }
            else if("false".equals(telePhoneStatus)){
                userListVoList = userListVoList.stream().filter(user ->{
                    return user.getTelePhone().equals("false");
                }).collect(Collectors.toList());
            }
        }
        Integer total = userListVoList.size();
        if(userListVoList.size() > 0){
            userListVoList = ListUtil.page(current-1,pageSize,userListVoList);
            return new PageVo<AdminUserListVo>(userListVoList,BooleanUtil.isTrue(userListVoList.size() > 0),
                    messageConstant.QUERY_SUCCESS, total);
        }
        else{
            return new PageVo<AdminUserListVo>(userListVoList,BooleanUtil.isFalse(userListVoList.size() == 0),
                    messageConstant.QUERY_NULL, total);
        }
    }

    @Override
    public Result addUser(Map<String, Object> user) throws Exception {
        //判断账号是否已经被使用
        System.out.println("user:"+user);
        if(ObjectUtil.isNotNull(iUserInfoService.getUserInfoByUsername((String) user.get("userName")))){
            UserInfo userInfo1 = iUserInfoService.getUserInfoByUsername((String) user.get("userName"));
            if(userInfo1.getUserName().equals((String) user.get("userName"))) {
                return Result.fail(false, messageConstant.USERNAME_USED);
            }
        }
        //判断昵称是否被使用
        if(ObjectUtil.isNotNull(iUserInfoService.getUserInfoByNickname((String) user.get("nickName")))){
            UserInfo userInfo2 = iUserInfoService.getUserInfoByNickname((String) user.get("nickName"));
            if(userInfo2.getNickName().equals((String) user.get("nickName"))) {
                return Result.fail(false, messageConstant.NICKNAME_USED);
            }
        }
        //判断电话是否被使用
        if(ObjectUtil.isNotNull(iUserInfoService.getUserInfoByTelephone((String) user.get("telePhone")))){
            UserInfo userInfo3 = iUserInfoService.getUserInfoByTelephone((String) user.get("telePhone"));
            if(userInfo3.getTelePhone().equals((String) user.get("telePhone"))) {
                return Result.fail(false, messageConstant.TELEPHONE_USED);
            }
        }


        return registerUser(user);
    }

    @Override
    public Result updateUser(String uId,Map<String, Object> user) throws Exception {
        System.out.println("user:"+user);
        UserInfo saveUserInfo = BeanUtil.fillBeanWithMap(user,new UserInfo(),false);
        saveUserInfo.setUId(uId);
        System.out.println("saveUserInfo:"+saveUserInfo);
        saveUserInfo.setPassWord(new BCryptPasswordEncoder().encode(saveUserInfo.getPassWord()));
        Boolean flag = iUserInfoService.updateById(saveUserInfo);
        if(flag){
            //修改用户权限
            if(user.get("role").equals("用户")){
                iUserRoleService.lambdaUpdate().eq(UserRole::getUId,saveUserInfo.getUId())
                        .set(UserRole::getRole,"ROLE_USER")
                        .update();
            }
            else if(user.get("role").equals("管理员")){
                iUserRoleService.lambdaUpdate().eq(UserRole::getUId,saveUserInfo.getUId())
                        .set(UserRole::getRole,"ROLE_ADMIN")
                        .update();
            }
            //修改用户基本资料
            iUserDetailService.lambdaUpdate().eq(UserDetail::getUId,uId)
                            .update(UserDetail.builder().sign((String) user.get("sign"))
                            .avatar((String) user.get("avatar"))
                            .build());
            return Result.success(true,messageConstant.UPDATE_SUCCESS);
        }
        else{
            return Result.fail(false,messageConstant.UPDATE_ERROR);
        }
    }

    @Override
    public Result getAdminUserDetailByUid(String uId) {
        UserInfo userInfo = iUserInfoService.getUserById(uId);
        AdminUserListVo adminUserListVo = AdminUserListVo.builder().build();
        BeanUtils.copyProperties(userInfo,adminUserListVo);
        //电话
        if(ObjectUtil.isNull(adminUserListVo.getTelePhone())){
            adminUserListVo.setTelePhone("false");
        }
        //密码
        if(ObjectUtil.isNull(adminUserListVo.getPassWord())){
            adminUserListVo.setPassWord("false");
        }
        //查询用户角色
        if(iUserRoleService.lambdaQuery().eq(UserRole::getUId,userInfo.getUId()).count() > 0){
            List<UserRole> userRoles = iUserRoleService.lambdaQuery().eq(UserRole::getUId,userInfo.getUId()).list();
            List<String> roles = userRoles.stream().map(Role -> {return Role.getRole();}).collect(Collectors.toList());
            System.out.println("roles:"+roles);
            if(roles.indexOf("ROLE_ADMIN") != -1){
                adminUserListVo.setRole("admin");
            }
            else{
                adminUserListVo.setRole("user");
            }
        }
        else{
            adminUserListVo.setRole("unassigned");
        }
        //根据role、password、telephone判断账户是否可用
        if((StrUtil.isNotBlank(userInfo.getPassWord()) && ObjectUtil.isNotNull(userInfo.getPassWord())) &&
                BooleanUtil.isTrue(!adminUserListVo.getRole().equals("unassigned")) &&
                (StrUtil.isNotBlank(userInfo.getTelePhone()) && ObjectUtil.isNotNull(userInfo.getTelePhone()))){
            adminUserListVo.setStatus(true);
        }
        else{
            adminUserListVo.setStatus(false);
        }
        //用户头像
        adminUserListVo.setAvatar(iUserDetailService.getUserDetailById(userInfo.getUId()).getAvatar());
        //个人签名
        adminUserListVo.setSign(iUserDetailService.getUserDetailById(userInfo.getUId()).getSign());
        return Result.success(adminUserListVo,ObjectUtil.isNotNull(adminUserListVo),messageConstant.QUERY_SUCCESS);
    }

    @Override
    @Transactional
    public Result deleteUserByUid(String uId) {
        // 根据uId删除userInfo相关信息
        iUserInfoService.lambdaUpdate().eq(UserInfo::getUId,uId).remove();
        Long total1 = iUserInfoService.lambdaQuery().eq(UserInfo::getUId,uId).count();
        // 根据uId删除userInfoMapping相关信息
        iUserInfoMappingService.deleteUserInfoByUid(uId);
        Long total2 = iUserInfoMappingService.getCount(uId);
        // 根据uId删除userRole相关的信息
        iUserRoleService.lambdaUpdate().eq(UserRole::getUId,uId).remove();
        Long total3 = iUserRoleService.lambdaQuery().eq(UserRole::getUId,uId).count();
        // 根据uId删除userDetail表中的相关信息
        iUserDetailService.lambdaUpdate().eq(UserDetail::getUId,uId).remove();
        Long total4 = iUserDetailService.lambdaQuery().eq(UserDetail::getUId,uId).count();
        if(total1 == 0 && total2 == 0 && total3 == 0 && total4 == 0){
            return Result.success(true,messageConstant.DELETE_SUCCESS);
        }
        else{
            return Result.fail(false,messageConstant.DELETE_ERROR);
        }
    }

    @Override
    public Result getModelTypeList() {
        List<ModelType> modelTypes = iModelTypeService.list();
        if(modelTypes.size() > 0){
            return Result.success(modelTypes,true,messageConstant.QUERY_SUCCESS);
        }
        else{
            return Result.fail(false,messageConstant.QUERY_ERROR);
        }
    }

    @Override
    public Result addModelInfo(Model model,AdminModelDto adminModelDto) {
        //添加信息
        ModelInfo modelInfo = ModelInfo.builder().build();
        BeanUtils.copyProperties(adminModelDto,modelInfo);
        modelInfo.setMId(model.getMId());
        Boolean flag = iModelInfoService.save(modelInfo);
        if(flag){
            return Result.success(true,messageConstant.INSERT_SUCCESS);
        }
        else{
            return Result.fail(false,messageConstant.INSERT_ERROR);
        }
    }

    @Override
    public ModelInfo getModelInfo(String mId) {
        ModelInfo modelInfo = iModelInfoService.lambdaQuery().eq(ModelInfo::getMId,mId).one();
        return modelInfo;
    }

    @Override
    public Result updateModelInfo(String mId, AdminModelDto adminModelDto) {
        ModelInfo modelInfo = ModelInfo.builder().mId(mId).build();
        BeanUtils.copyProperties(adminModelDto,modelInfo);
        //修改modelInfo表信息
        Boolean flag = iModelInfoService.lambdaUpdate().eq(ModelInfo::getMId,mId).update(modelInfo);
        if(flag){
            return Result.success(true,messageConstant.UPDATE_SUCCESS);
        }
        else{
            return Result.fail(false,messageConstant.UPDATE_ERROR);
        }
    }

    @Override
    public Result deleteModelInfo(String mId) {
        //删除modelInfo表中内容
        Boolean flag = iModelInfoService.lambdaUpdate().eq(ModelInfo::getMId,mId).remove();
        if(flag){
            return Result.success(true,messageConstant.DELETE_SUCCESS);
        }
        else{
            return Result.fail(false,messageConstant.DELETE_ERROR);
        }
    }

    @Override
    public PageVo<UserDetailVo> getArticleAuthorList(Integer current, Integer pageSize) {
        IPage page = new Page<UserDetailVo>(current,pageSize);
        List<UserInfo> articleList = iUserInfoService.page(page).getRecords();
        List<UserDetailVo> userDetailVoList = articleList.stream().map(article -> {
            UserDetailVo userDetailVo = UserDetailVo.builder().build();
            BeanUtils.copyProperties(article,userDetailVo);
            return userDetailVo;
        }).collect(Collectors.toList());
        if(userDetailVoList.size() > 0){
            return new PageVo<UserDetailVo>(userDetailVoList,true,messageConstant.QUERY_SUCCESS, (int) page.getTotal());
        }
        else
            return new PageVo<UserDetailVo>(null,false,messageConstant.QUERY_ERROR, (int) page.getTotal());
    }

    @Override
    public PageVo<UserDetailVo> getArticleAuthorListByKeyWord(Integer current, Integer pageSize, String keyWord) {
        List<UserInfo> articleList = iUserInfoService.list();
        List<UserDetailVo> userDetailVoList = articleList.stream().map(article -> {
            UserDetailVo userDetailVo = UserDetailVo.builder().build();
            BeanUtils.copyProperties(article,userDetailVo);
            return userDetailVo;
        }).collect(Collectors.toList());
        userDetailVoList = userDetailVoList.stream().filter(userDetailVo -> {
            return userDetailVo.getNickName().contains(keyWord);
        }).collect(Collectors.toList());
        Integer total = userDetailVoList.size();
        userDetailVoList = ListUtil.page(current - 1,pageSize,userDetailVoList);
        return new PageVo<UserDetailVo>(userDetailVoList,true,messageConstant.QUERY_SUCCESS, total);
        /*else
            return new PageVo<UserDetailVo>(null,false,messageConstant.QUERY_ERROR, total);*/
    }

    @Override
    public List<AdminArticleListVo> getArticleList(Integer current, Integer pageSize,
                                                   String title, String author, String publishTime) {
        List<Article> articleList;
        List<AdminArticleListVo> adminArticleListVos;
       if((title != null && !title.trim().equals("")) || (author != null && !author.trim().equals("")) ||
           publishTime != null && !publishTime.trim().equals("")){
           articleList = iArticleService.lambdaQuery().and(i ->
                         i.like(title != null && !title.trim().equals(""),
                         Article::getTitle,title)
                         .like(author != null && !author.trim().equals(""),
                         Article::getUId,author)
                         .like(publishTime != null && !publishTime.trim().equals(""),
                         Article::getPublishTime,publishTime)).list();
           adminArticleListVos = articleList.stream().map(article -> {
               AdminArticleListVo adminArticleListVo = AdminArticleListVo.builder().build();
               BeanUtils.copyProperties(article,adminArticleListVo);
               //根据用户id查询用户昵称
               String nickName = iUserInfoService.getUserById(article.getUId()).getNickName();
               adminArticleListVo.setNickName(nickName);
               return adminArticleListVo;
           }).collect(Collectors.toList());
       }
       else{
           articleList = iArticleService.list();
           adminArticleListVos = articleList.stream().map(article -> {
               AdminArticleListVo adminArticleListVo = AdminArticleListVo.builder().build();
               BeanUtils.copyProperties(article,adminArticleListVo);
               //根据用户id查询用户昵称
               String nickName = iUserInfoService.getUserById(article.getUId()).getNickName();
               adminArticleListVo.setNickName(nickName);
               return adminArticleListVo;
           }).collect(Collectors.toList());
       }
        return adminArticleListVos;
        /* List<Article> articleList = iArticleService.list();
        List<AdminArticleListVo> adminArticleListVos = articleList.stream().map(article -> {
            AdminArticleListVo adminArticleListVo = AdminArticleListVo.builder().build();
            BeanUtils.copyProperties(article,adminArticleListVo);
            //根据用户id查询用户昵称
            String nickName = iUserInfoService.getUserById(article.getUId()).getNickName();
            adminArticleListVo.setNickName(nickName);
            return adminArticleListVo;
        }).collect(Collectors.toList());
        return adminArticleListVos;*/
    }

    @Override
    public AdminArticleDetailVo getArticleByAid(Integer aId) {
        Article article = iArticleService.getArticleByAid(aId);
        AdminArticleDetailVo adminArticleDetailVo = AdminArticleDetailVo.builder().build();
        BeanUtils.copyProperties(article,adminArticleDetailVo);
        String avatar= iUserDetailService.lambdaQuery().eq(UserDetail::getUId,article.getUId()).one().getAvatar();
        adminArticleDetailVo.setSrc(avatar);
        String nickName = iUserInfoService.getUserById(article.getUId()).getNickName();
        adminArticleDetailVo.setNickName(nickName);
        return adminArticleDetailVo;
    }

    @Override
    public Boolean addArticleInfo(AdminArticleDto adminArticleDto) {
        Article article = Article.builder().build();
        BeanUtils.copyProperties(adminArticleDto,article);
        article.setWatch(0);
        return iArticleService.save(article);
    }

    @Override
    public Article getArticleByaId(Integer aId) {
        Article article = iArticleService.lambdaQuery().eq(Article::getAId,aId).one();
        return article;
    }

    @Override
    public Boolean updateArticleInfo(Integer aId,AdminArticleDto adminArticleDto) {
        Article article = Article.builder().build();
        BeanUtils.copyProperties(adminArticleDto,article);
        article.setAId(aId);
        article.setPublishTime(this.getArticleByaId(aId).getPublishTime());
        return iArticleService.updateById(article);
    }

    @Override
    public Boolean DeleteArticleByAid(Integer aId) {
        return iArticleService.lambdaUpdate().eq(Article::getAId,aId).remove();
    }

    @Override
    public List<UserDetailVo> getArticleAuthorUpdateList(Integer current, Integer pageSize) {
        List<UserInfo> articleList = iUserInfoService.list();
        List<UserDetailVo> userDetailVoList = articleList.stream().map(article -> {
            UserDetailVo userDetailVo = UserDetailVo.builder().build();
            BeanUtils.copyProperties(article,userDetailVo);
            return userDetailVo;
        }).collect(Collectors.toList());
        if(userDetailVoList.size() > 0){
            return userDetailVoList;
        }
        else
            return null;
    }

    @Override
    public UserInfo getUserInfo(String uId) {
        UserInfo userInfo = iUserInfoService.lambdaQuery().eq(UserInfo::getUId,uId).one();
        return userInfo;
    }

    //注册用户
    @Transactional
    public Result registerUser(Map<String, Object> user) throws Exception {
        //将昵称、账号、加密的密码、电话存入userinfo表
        System.out.println("user:"+user);
        UserInfo saveUserInfo = BeanUtil.fillBeanWithMap(user,new UserInfo(),false);
        System.out.println("saveUserInfo:"+saveUserInfo);
        saveUserInfo.setPassWord(new BCryptPasswordEncoder().encode(saveUserInfo.getPassWord()));
        UserInfo userInfo = iUserInfoService.insertANDGetUid(saveUserInfo);
        if(ObjectUtil.isNotNull(userInfo)){
            System.out.println("userInfo:"+userInfo);
            //将用户id映射存入userInfoMapping表
            iUserInfoMappingService.save(UserInfoMapping.builder().uId(userInfo.getUId()).build());
            //给用户权限
            if(user.get("role").equals("用户")){
                iUserRoleService.save(UserRole.builder().uId(userInfo.getUId()).role("ROLE_USER").build());
            }
            else if(user.get("role").equals("管理员")){
                iUserRoleService.save(UserRole.builder().uId(userInfo.getUId()).role("ROLE_ADMIN").build());
            }
            //给用户添加默认的详细信息
            iUserDetailService.save(UserDetail.builder()
                    .uId(userInfo.getUId())
                    .sign((String) user.get("sign"))
                    .avatar((String) user.get("avatar"))
                    .build());
            return Result.success(userInfo.getUId(),true,messageConstant.REGISTER_SUCCESS);
        }
        else{
            return Result.fail(false,messageConstant.REGISTER_ERROR);
        }
    }
}
